package com.rr.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuangcanrun
 * @Date 2022/10/07/14:18
 * @description
 **/

/*
* 死信队列做延迟队列demo
* */
@Component
@Slf4j
public class Demo2DeadQueueTest {

    private static final String DEAD_EXCHANGE = "dead_exchange";
    private static final String DEAD_QUEUE = "dead_queue";
    private static final String DEAD_ROUTINE_KEY = "dead_routine_key";

    private static final String BUSINESS_EXCHANGE = "business_exchange";
    private static final String BUSINESS_QUEUE = "business_queue";
    private static final String BUSINESS_ROUTINE_KEY = "business_routine_key";

    @RabbitListener(
            queues = BUSINESS_QUEUE
    )
    public void onMessage(Message message, Channel channel) throws IOException {
        try {
            String messages = new String(message.getBody(), StandardCharsets.UTF_8);
            System.out.println(messages);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }

    @Bean
    public Exchange deadExchange() {
        return ExchangeBuilder.directExchange(DEAD_EXCHANGE).durable(true).build();
    }

    @Bean
    public Exchange businessExchange() {
        return ExchangeBuilder.directExchange(BUSINESS_EXCHANGE).durable(true).build();
    }

    @Bean
    public Queue deadQueue() {
        Map<String, Object> args = new HashMap<>(4);
        args.put("x-dead-letter-exchange", BUSINESS_EXCHANGE);
        args.put("x-dead-letter-routing-key", BUSINESS_ROUTINE_KEY);
        args.put("x-message-ttl", 5000);
        return QueueBuilder.durable(DEAD_QUEUE).withArguments(args).build();
    }

    @Bean
    public Queue businessQueue() {
        return QueueBuilder.durable(BUSINESS_QUEUE).build();
    }

    @Bean
    public Binding deadBinding() {
        return new Binding(DEAD_QUEUE, Binding.DestinationType.QUEUE,
                DEAD_EXCHANGE, DEAD_ROUTINE_KEY, null);
    }

    @Bean
    public Binding businessBinding() {
        return new Binding(BUSINESS_QUEUE, Binding.DestinationType.QUEUE,
                BUSINESS_EXCHANGE, BUSINESS_ROUTINE_KEY, null);
    }
}
